package com.shiro.test.mvc.service.impl;

import com.shiro.test.mvc.dao.IBaseDao;
import com.shiro.test.mvc.mapper.MenuMapper;
import com.shiro.test.mvc.pojo.Menu;
import com.shiro.test.mvc.pojo.MenuPermission;
import com.shiro.test.mvc.pojo.User;
import com.shiro.test.mvc.service.IBaseService;
import com.shiro.test.mvc.service.IMenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2020/11/27 0027.
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService{

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public IBaseDao<Menu> getDao() {
        return menuMapper;
    }

    @Override
    public List<Menu> getTreeMenu() {
        List<Menu> menus = menuMapper.getAllMenu();
        Map<Integer,Menu> menuMap = new HashMap<>(menus.size());
        List<Menu> parentMenu = new ArrayList<>();
        for (Menu menu : menus) {
            menuMap.put(menu.getId(),menu);
            if (menu.getParentId() == null){
                parentMenu.add(menu);
            }
        }
        for (Menu menu : menus) {
            if (menu.getParentId() != null){
                Menu parent = menuMap.get(menu.getParentId());
                parent.getChildren().add(menu);
            }
        }
        return parentMenu;

    }

    @Override
    public List<Menu> myTreeMenu(Integer userId) {
        List<Menu> menus = menuMapper.getMenuPermsByUser(userId);
        Map<Integer,Menu> menuMap = new HashMap<>(menus.size());
        List<Menu> parentMenu = new ArrayList<>();
        for (Menu menu : menus) {
            menuMap.put(menu.getId(),menu);
            if (menu.getParentId() == null){
                parentMenu.add(menu);
            }
        }
        for (Menu menu : menus) {
            if (menu.getParentId() != null){
                Menu parent = menuMap.get(menu.getParentId());
                parent.getChildren().add(menu);
            }
        }
        return parentMenu;

    }

    @Override
    public List<MenuPermission> getMenuPerms() {
        return menuMapper.getMenuPerms();
    }
}
